package com.lhh.virus.service;

import com.lhh.virus.pojo.CountryVirusStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther 虎
 * @Data 2020/5/7 22:46
 * @Version 1.0
 */
@Service
public class VirusService implements InitializingBean{

    private static final String VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private List<CountryVirusStats> allCountryVirusStats = new ArrayList<>();

    public List<CountryVirusStats> getAllCountryVirusStats(){return allCountryVirusStats;}

    CountryVirusStats countryVirusStats;
    /**
     * 每天凌晨2点更新数据；
     * @throws IOException
     */
    @Scheduled(cron = "${lhhu.updateVirusDataCron}")
    public void fetchVirusData() throws IOException{
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(VIRUS_DATA_URL))
                .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36")
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();
        InputStream inputStream = body.getInputStream();
        Reader reader = new InputStreamReader(inputStream);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader);
        int fact = 0;
        for (CSVRecord record : records) {
            if (fact == 0) {
                fact = 1;
                continue;
            }
            countryVirusStats = new CountryVirusStats();
            countryVirusStats.setState(record.get(0));
            countryVirusStats.setCountry(record.get(1));
            countryVirusStats.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
            countryVirusStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1))-Integer.parseInt(record.get(record.size() - 2)));
            allCountryVirusStats.add(countryVirusStats);
        }
        System.out.println(allCountryVirusStats);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchVirusData();
    }
}
